package com.wcy.app.lib.update;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;
import com.lxj.xpopup.util.XPopupUtils;
import com.wcy.app.lib.network.HttpJava;
import com.wcy.app.lib.network.interfaces.DownLoadResult;
import com.wcy.app.lib.update.interfaces.UpdateInterface;

import java.io.File;
import java.util.List;


/**
 * 版本更新弹框
 */
public final class UpdateDialog {
    public static final class Builder {
        private UpdatePopurView updatePopurView;
        private AppCompatActivity mContext;
        private UpdateInterface mCallBack;


        public Builder(@NonNull AppCompatActivity context) {
            mContext = context;
            updatePopurView = new UpdatePopurView(context);
        }

        public Builder setContent(VersionBean uploadBean) {
            updatePopurView.setContent(uploadBean);
            return this;
        }

        public Builder setUpdateInterface(UpdateInterface callBack) {
            mCallBack = callBack;
            return this;
        }

        public void show() {
            new XPopup.Builder(mContext).dismissOnBackPressed((mCallBack == null) ? true : false).dismissOnTouchOutside(false).asCustom(updatePopurView).show();
        }

        private class UpdatePopurView extends CenterPopupView {
            private VersionBean mVersionBean;

            /**
             * Apk 文件
             */
            private File mApkFile;
            /**
             * 当前是否下载中
             */
            private boolean mDownloading;
            /**
             * 当前是否下载完毕
             */
            private boolean mDownloadComplete;
            private ProgressBar mProgressView;
            TextView mCloseView, mUpdateView;
            View viewline;

            public UpdatePopurView(@NonNull Context context) {
                super(context);
            }

            @Override
            protected int getImplLayoutId() {
                return R.layout.update_dialog;
            }

            @Override
            protected void initPopupContent() {
                super.initPopupContent();
                mCloseView = findViewById(R.id.btn_cancel);
                mUpdateView = findViewById(R.id.btn_commit);
                viewline = findViewById(R.id.view_line);
                mProgressView = findViewById(R.id.pb_update_progress);
                setText(R.id.tv_title, mVersionBean.title);
                setText(R.id.tv_version, mVersionBean.versionNum);
                setText(R.id.tv_apksize, mVersionBean.apkSize);
                setText(R.id.tv_updatecreate, mVersionBean.createDate);
                setText(R.id.tv_msg, mVersionBean.getUpdateContent());
                if (mVersionBean.is_must_update) {
                    mCloseView.setClickable(false);
                    viewline.setVisibility(android.view.View.GONE);
                    mCloseView.setVisibility(View.GONE);
                }
                mCloseView.setOnClickListener(v -> dismissWith(() -> {
                    if (mCallBack != null) mCallBack.succeed();
                }));
                mUpdateView.setOnClickListener(v -> {
                    // 判断下载状态
                    if (mDownloadComplete) {
                        if (mApkFile.isFile()) {
                            // 下载完毕，安装 Apk
                            installApk();
                        } else {
                            // 下载失败，重新下载
                            downloadApk();
                        }
                    } else if (!mDownloading) {
                        // 没有下载，开启下载
                        downloadApk();
                    }
                });
            }

            protected int getMaxWidth() {
                return popupInfo.maxWidth==0 ? (int) (XPopupUtils.getWindowWidth(getContext()) * 0.9f)
                        : popupInfo.maxWidth;
            }
            public void setContent(VersionBean uploadBean) {
                mVersionBean = uploadBean;
            }

            private void setText(int id, String msg) {
                if (!TextUtils.isEmpty(msg)) {
                    TextView textView = findViewById(id);
                    if (TextUtils.isEmpty(textView.getText().toString())) textView.setText(msg);
                    else textView.append(msg);
                    textView.setVisibility(View.VISIBLE);
                    textView.setMovementMethod(ScrollingMovementMethod.getInstance());
                }
            }

            /**
             * 下载 Apk
             */
            private void downloadApk() {
                // 创建要下载的文件对象
                mApkFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), getContext().getString(R.string.app_name) + "_v" + mVersionBean.versionNum + ".apk");
                XXPermissions.with(mContext)
                        .permission(Permission.Group.STORAGE)
                        .request(new OnPermission() {
                            @Override
                            public void hasPermission(List<String> granted, boolean isAll) {
                                // 标记为下载中
                                mDownloading = true;
                                // 标记成未下载完成
                                mDownloadComplete = false;
                                // 后台更新
                                mCloseView.setVisibility(View.GONE);
                                viewline.setVisibility(android.view.View.GONE);
                                mProgressView.setProgress(0);
                                // 显示进度条
                                mProgressView.setVisibility(View.VISIBLE);
                                mUpdateView.setText(R.string.update_status_start);
                                HttpJava.downloadFile(mVersionBean.download_url, mApkFile.getAbsolutePath(),mContext, new DownLoadResult<String>() {
                                    @Override
                                    public void onNext(String s) {
                                        mUpdateView.setText(R.string.update_status_successful);
                                        // 标记成下载完成
                                        mDownloadComplete = true;
                                        // 标记当前不是下载中
                                        mDownloading = false;
                                        // 安装 Apk
                                        installApk();
                                    }

                                    @Override
                                    public void onError(Throwable throwable) {
                                        // 标记成未下载完成
                                        mDownloadComplete = false;
                                        mDownloading = false;
                                        mUpdateView.setText(R.string.update_status_failed);
                                        // 删除下载的文件
                                        mApkFile.delete();
                                    }

                                    @Override
                                    public void Progress(int progress, long currentSize, long totalSize) {
                                        mUpdateView.setText(String.format(getContext().getString(R.string.update_status_running), progress));
                                        mProgressView.setProgress(progress);
                                    }
                                });
                            }

                            @Override
                            public void noPermission(List<String> denied, boolean quick) {
                                Toast.makeText(getContext(), "请先授予权限", Toast.LENGTH_SHORT).show();
                            }
                        });
            }

            /**
             * 安装 Apk
             */
            private void installApk() {
                XXPermissions.with(mContext)
                        .permission(Permission.REQUEST_INSTALL_PACKAGES)
                        .request(new OnPermission() {
                            @Override
                            public void hasPermission(List<String> granted, boolean isAll) {
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_VIEW);
                                Uri uri;
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", mApkFile);
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                } else {
                                    uri = Uri.fromFile(mApkFile);
                                }
                                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                getContext().startActivity(intent);
                            }

                            @Override
                            public void noPermission(List<String> denied, boolean quick) {
                                Toast.makeText(getContext(), "请先授予权限", Toast.LENGTH_SHORT).show();
                            }
                        });
            }
        }
    }

}
